package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.ResponseProcessorImp;

import java.util.Date;
import java.util.concurrent.BlockingQueue;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressValue;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ReadCoilsRequest;
import net.wimpi.modbus.msg.ReadCoilsResponse;
import net.wimpi.modbus.procimg.DigitalOut;
import net.wimpi.modbus.procimg.SimpleDigitalOut;
import net.wimpi.modbus.util.BitVector;

public class ReadCoilsResponseProcessor extends AbstractResponseProcessor {
	
	private static final Integer INT_1 = new Integer(1);
	private static final Integer INT_0 = new Integer(0);

	@Override
	public void processResponse(ModbusRequest req, ModbusResponse res, BlockingQueue<AddressValue> queue) {
		
		//TODO: ReadCoilsResponseProcessor errores IllegalAddressException
		if(res instanceof ReadCoilsResponse && req instanceof ReadCoilsRequest) {
			
			BitVector bits = ((ReadCoilsResponse) res).getCoils();
			int baseDir = ((ReadCoilsRequest)req).getReference();
			int bitCount = ((ReadCoilsRequest)req).getBitCount();
			Date date = new Date();
			
			for(int i = 0; i < bitCount; i++){
				
				int address = baseDir + i;

				DigitalOut value = new SimpleDigitalOut(bits.getBit(i));
				
				AddressValue newValue = new AddressValue();
				newValue.setAddress(address);
				newValue.setAddressType(AddressType.COIL);
				newValue.setDate(date);
				if(value.isSet())
				   newValue.setValue(INT_1);
				else
				   newValue.setValue(INT_0);
				
				queue.add(newValue);
				
				getImage().setDigitalOut(address,value,date);
				
				//TODO: Descomentar 
				/*
				
				if( getDeciveDAO() != null )
					if(value.isSet())
						getDeciveDAO().saveValue( getDevice(), address ,INT_1 , AddressType.COIL );
					else
						getDeciveDAO().saveValue( getDevice(), address ,INT_0 , AddressType.COIL );
				
				*/	
			}
			
		}
		
	}

}
